package cn.ynu.cmrs.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;

import cn.ynu.cmrs.R;
import cn.ynu.cmrs.AppConstant;
import cn.ynu.cmrs.MyApplication;
import cn.ynu.cmrs.adapter.CourseAdapter;
import cn.ynu.cmrs.asyncTask.GetInfosTask;
import cn.ynu.cmrs.model.Course;
import cn.ynu.cmrs.model.CourseInfoItem;
import cn.ynu.cmrs.utils.JsonParse;
import cn.ynu.cmrs.utils.WebInterface;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ViewFlipper;

/**
 * Activity allows user search course by course name or teacher name
 * 
 * @author Yasha
 * 
 */
public class SearchActivity extends Activity {

	/**
	 * Flag indicates whether the user had clicked "see more"
	 */
	private boolean getMoreFlag = false;
	public static int SEARCH_BY_COURSE = 0;
	public static int SEARCH_BY_TEACHER = 1;

	private AutoCompleteTextView act;
	private Button searchButton;
	private ListView searchedCourses;
	private RadioGroup mRadioGroup;
	private ViewFlipper mViewFlipper;

	/**
	 * The pages of course has displayed
	 */
	public int nowpage = 1;
	/**
	 * The amount of courses
	 */
	public int totalItemsCount = 0;
	/**
	 * The amount of courses had got
	 */
	public int existingItemsCount = 0;
	/**
	 * The manner of search course
	 */
	private int searchMode = SEARCH_BY_COURSE;
	private int tempSearchMode = SEARCH_BY_COURSE;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyApplication.allActivity.add(this);
		setContentView(R.layout.search);
		prepareView();
		setListener();
	}

	private void setListener() {
		mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch (checkedId) {
				case R.id.rbSearchCourse:
					searchMode = SEARCH_BY_COURSE;
					break;
				case R.id.rbSearchTeacher:
					searchMode = SEARCH_BY_TEACHER;
					break;
				default:
					searchMode = SEARCH_BY_COURSE;
					break;
				}
			}
		});
		searchButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!(act.getText().toString().equals(""))) {
					nowpage = 1;
					tempSearchMode = searchMode;
					new SearchCoursesTask(SearchActivity.this,
							R.string.fail_general, null).execute(searchMode);
					searchButton.setEnabled(false);
				} else {
					Toast.makeText(SearchActivity.this, R.string.keyword_null,
							Toast.LENGTH_LONG).show();
				}
			}
		});

		searchedCourses.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if (id == -1) {
					if (!getMoreFlag) {
						if (existingItemsCount >= totalItemsCount) {
							Toast.makeText(SearchActivity.this,
									R.string.no_moreitems, Toast.LENGTH_SHORT).show();
						} else {
							new SearchCoursesTask(SearchActivity.this,
									R.string.fail_general, null)
									.execute(tempSearchMode);
						}
					}
				}
			}

		});
	}

	private void prepareView() {
		mRadioGroup = (RadioGroup) findViewById(R.id.search_radio);
		act = (AutoCompleteTextView) findViewById(R.id.SearchACTextView);
		searchButton = (Button) findViewById(R.id.SearchButton);
		searchedCourses = (ListView) findViewById(R.id.SearchListView);
		mViewFlipper = (ViewFlipper) findViewById(R.id.SearchViewFlipper);
		if (searchedCourses.getCount() == 0) {
			mViewFlipper.setDisplayedChild(2); // search list hint
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		// Capture the back button to prompt exit
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			MyApplication.promptExitApp(this);
		}
		return true;
	}

	/**
	 * AsyncTask class, post search request to server
	 * 
	 * @author Yasha
	 * 
	 */
	private class SearchCoursesTask extends GetInfosTask<Integer, Course> {

		public SearchCoursesTask(Activity mActivity, int mFailMsg, View mView) {
			super(mActivity, mFailMsg, mView);
		}

		@Override
		protected Course doInBackground(Integer... arg0) {
			// TODO Auto-generated method stub
			Map<String, String> param = new HashMap<String, String>();
			param.clear();
			param.put("interface", "getcourse");
			switch (arg0[0]) {
			case 0:
				param.put("by", "title");
				break;
			case 1:
				param.put("by", "teacher");
				break;
			}
			param.put("addition", act.getText().toString());
			param.put(
					"start",
					String.valueOf((nowpage - 1)
							* AppConstant.MostUsedConstant.pageSize + 1));
			param.put("amount",
					String.valueOf(AppConstant.MostUsedConstant.pageSize));
			String result = WebInterface.webInterface(param);
			Log.i("searchCourses", result);
			Course courses;
			try {
				courses = JsonParse.getCourse(result);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				courses = new Course(null, null, new String[] { "8086",
						mActivity.getString(R.string.inner_error_json) });
			}
			return courses;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(Course result) {
			// TODO Auto-generated method stub
			String[] status = result.getStatus();
			if (status[0].equals("0")) {
				doStuffWithResult(result);
			} else {
				failMsg(status[1]);
			}
			searchButton.setEnabled(true);
		}

		@Override
		protected void doStuffWithResult(Course result) {
			// TODO Auto-generated method stub
			mViewFlipper = (ViewFlipper) findViewById(R.id.SearchViewFlipper);
			ArrayList<CourseInfoItem> items;
			if (nowpage == 1) {
				if (result.getItems() == null || result.getItems().size() == 0) {
					items = new ArrayList<CourseInfoItem>();
					totalItemsCount = 0;
					existingItemsCount = 0;
					mViewFlipper.setDisplayedChild(1);
				} else {
					items = new ArrayList<CourseInfoItem>(result.getItems());
					totalItemsCount = items.size();
					existingItemsCount = items.size();
					CourseAdapter myCourseAdapter = new CourseAdapter(
							mActivity, items, searchedCourses);
					searchedCourses.setAdapter(myCourseAdapter);
					mViewFlipper.setDisplayedChild(0);
				}
			} else {
				if (result.getItems() != null && result.getItems().size() >= 0) {
					existingItemsCount += result.getItems().size();
					((CourseAdapter) searchedCourses.getAdapter())
							.addMoreData(new ArrayList<CourseInfoItem>(result
									.getItems()));
					nowpage++;
				}
			}
			getMoreFlag = false;
		}
	}

	/**
	 * Launch this Activity from the outside
	 * 
	 * @param context
	 *            context from which Activity should be started
	 */
	public static void launch(Context context) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(context, SearchActivity.class);
		context.startActivity(intent);
	}

}
